package net.xumf.dao.master;

import net.xumf.domain.master.Dict;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

public interface DictRepository extends PagingAndSortingRepository<Dict, Integer> {

    @Transactional
    @Modifying
    void deleteByParentId(Integer parentId);

    long countByParentId(Integer parentId);

    Page<Dict> findAllByParentId(Integer parentId, Pageable pageable);

    List<Dict> findAllByParentIdOrderBySequenceAsc(Integer parentId);

    /**
     * 通过父key，获取子字典列表
     * @param parentKey 父key
     * @return 子字典列表
     */
    @Query(value = "SELECT new Dict(d.name, d.value) FROM Dict d JOIN Dict pd ON d.parentId = pd.dictId AND pd.key = ?1")
    List<Dict> findAllByParentKey(String parentKey);

    /**
     * 通过key获取字典的值
     * @param key 键
     * @return 字典值
     */
    @Query(value = "SELECT new Dict(d.value) from Dict d where d.key = ?1")
    Optional<Dict> findByKey(String key);
}